

#ifndef _imt_network_h_
#define _imt_network_h_

#include "imtPublic.h"
#include "imtCommand.h"
#include "imtListener.h"
#include "OgreTimer.h"

namespace iMate {

	class Client;

	class _iMateExport Network : public Singleton<Network>, public NormalAlloc
	{
		typedef TBaseListener2Args<Network, const NullCmd*, size_t> CmdHandler;
		typedef HashMap<cmdtt, CmdHandler*> CmdHandlerList;
		typedef CmdHandlerList::iterator CmdHandlerIteraotr;
	public:
		Network() : mClient(0){}
		~Network() {release();clearAllHandlers();}
	
		/** initialise network
		@param server    server address: a numeric host address string 
		  @par dotted-decimal IPv4 address or an IPv6 hex address
		@param port     a numeric string
		@return   success to true
		*/
		bool init(const String& server, const String& port);
		///release everything
		void release();

		/**connect to server asigned by setServerInfo(@see setServerInfo)
		@return true if connection success
		*/
		bool connect();
		///disconnect from server
		void disconnect();

		/**handle the cmds in the message queue
		@param maxHandleTime   the max time cosumed in handling messages
		       @par if time out, the function returns
		*/
		void handleCmds(ulong maxHandleTime =(ulong)-1L);

		/**handle one single cmd
		@param cmd  the cmd to be handled
		@param size   the size of the cmd
		@return true if handled successfully
		*/
		bool handleCmd(const NullCmd* cmd, size_t size);

		/**send cmd
	    @param cmd    a complete cmd
		@param size   the size of cmd
		@param toSelf   send it to server if false, otherwise push it to receive-message 
		     @par queue to simulating a message's arrival from server
	    @return true if send successfully
		*/
		bool sendCmd(const NullCmd* cmd, size_t size, bool toSelf = false);

		/**setup a handler for a special type of cmd
		@param cmdType   the type of cmd to be setup
		@param handler   the cmd handler to be set, 
		    @Note the previous handler will be unload even if "handler" is null
		@return  true if success
		*/
		bool setupCmdHandler(cmdtt cmdType, CmdHandler* handler);

		///clear and delete handlers
		void clearAllHandlers();

	protected:
		///the tool for receive and parse message
		Client* mClient;
		///the cmd handlers for each type of cmd
		CmdHandlerList mCmdHandlers;
		///timer
		Timer mTimer;

	public:
        /** Override standard Singleton retrieval.
        */
        static Network& getSingleton(void);
        /** Override standard Singleton retrieval.
        */
        static Network* getSingletonPtr(void);
	};

}//iMate









#endif //_imt_network_h_